#pragma once
#include <pthread.h>
#include <string>
#include <functional>

namespace kzz
{
    static int num = 1;
    class Thread
    {
        using func_t = std::function<void()>;

    private:
        void Enabledetach()
        {
            _isdetach = true;
        }
        void Enablerunning()
        {
            _isrunning = true;
        }

    public:
        Thread(func_t func)
            : _tid(0), _isrunning(false), _isdetach(false), _func(func)
        {
            _name = "thread--" + std::to_string(num++);
            printf("init %s\n",_name.c_str());
        }
        static void *routinue(void *args)
        {
            Thread *self = static_cast<Thread *>(args);
            printf("routinue success ,i am %s\n", self->_name.c_str());
            self->_func();
            return nullptr;
        }
        bool Start()
        {
            if (_isrunning)
                return false;
            int n = pthread_create(&_tid, nullptr, routinue, this);
            if (n != 0)
            {
                printf("pthread_create error\n");
                return false;
            }

            printf("pthread_create success,my name is %s\n",_name.c_str());

            Enablerunning();
            return true;
        }
        void detach()
        {
            if (_isdetach)
                return;
            if (_isrunning)
                pthread_detach(_tid);
            Enabledetach();
            return;
        }
        bool stop()
        {
            if (_isrunning)
            {
                int n = pthread_cancel(_tid);
                if (n != 0)
                {
                    printf("pthread_cacel error\n");
                    return true;
                }
                _isrunning = false;
                return true;
            }
            printf("线程: %s  还没运行，不能stop\n", _name.c_str());
            return false;
        }
        bool Join()
        {
            if (_isdetach)
            {
                printf("线程: %s 已分离，不能join", _name.c_str());
                return false;
            }

            int n = pthread_join(_tid, &res);
            if (n != 0)
            {
                printf("join false\n");
                return false;
            }
            printf("join success,my name is %s\n",_name.c_str());
            return true;
        }

        ~Thread()
        {
        }

    private:
        pthread_t _tid;
        std::string _name;
        bool _isdetach;
        bool _isrunning;
        void *res;
        func_t _func;
    };
}